﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BCGC.BLL.Helper;
using BCGC.BLL.BusinessObject.UserAccount;
using Jalal.Library.DataStructure;
using System.Collections.Generic;
using Jalal.Library.Utility;
using System.Drawing;

public partial class Admin_User_Default : AdminBasePage
{
    private int CurrentPageIndex
    {
        get
        {
            if (ViewState["CurrentPageIndex"] == null)
                ViewState["CurrentPageIndex"] = 1;
            return (int)ViewState["CurrentPageIndex"];
        }
        set { ViewState["CurrentPageIndex"] = value; }
    }

    private string SortOrder
    {
        get
        {
            if (ViewState["SortOrder"] == null)
                ViewState["SortOrder"] = "UserId";
            return (string)ViewState["SortOrder"];
        }
        set { ViewState["SortOrder"] = value; }
    }

    private int TotalData
    {
        get
        {
            if (ViewState["TotalData"] == null)
                ViewState["TotalData"] = 0;
            return (int)ViewState["TotalData"];
        }
        set { ViewState["TotalData"] = value; }
    }

    private void BindPager()
    {
        List<string> pages = new List<string>();
        int pageCount = (TotalData / grvUsers.PageSize) + ((TotalData % grvUsers.PageSize)>0? 1 : 0);
        for (int i = 1; i <= pageCount; i++)
            pages.Add(i.ToString());

        rptPager.DataSource = pages;
        rptPager.DataBind();
    }

    protected void Page_Change(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "PagingCommand")
        {
            CurrentPageIndex = Convert.ToInt32(e.CommandArgument);
            BindGrid();
            BindPager();
        }
    }

    protected void Grid_Sort(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "Sort")
        {
            grvUsers.EditIndex = -1;
            SortOrder = (string)e.CommandArgument;
            BindGrid();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitControls();
            BindGrid();
            BindPager();
        }
    }

    private void InitControls()
    {
        ReadWriteCustomCollection<UserRole> roles = UserRole.GetAllRoles();
        ddlRole.DataSource = roles;
        ddlRole.DataTextField = "RoleName";
        ddlRole.DataValueField = "Id";
        ddlRole.DataBind();
    }

    private void BindGrid()
    {
        int? roleId;
        if(string.IsNullOrEmpty(ddlRole.SelectedValue))
            roleId = null;
        else
            roleId = Security.BindIntegerInput(ddlRole.SelectedValue, SecurityLevel.Three);

        bool? isActive;
        if(ddlActive.SelectedValue == "-1")
            isActive = null;
        else
            isActive = Security.BindBooleanInput(ddlActive.SelectedValue, SecurityLevel.Three);

        bool? isLocked;
        if (ddlLocked.SelectedValue == "-1")
            isLocked = null;
        else
            isLocked = Security.BindBooleanInput(ddlLocked.SelectedValue, SecurityLevel.Three);

        int totalData = 0;
        ReadWriteCustomCollection<SiteUser> users = SiteUser.GetAllUsers(CurrentPageIndex, SortOrder, grvUsers.PageSize,
            string.IsNullOrEmpty(tbxUsername.Text) ? null : Security.BindStringInput(tbxUsername.Text, SecurityLevel.Three),
            roleId, regDateFrom.Date, regDateTo.Date, isActive, isLocked, out totalData );

        TotalData = totalData;

        grvUsers.DataSource = users;
        grvUsers.DataBind();
    }

    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox cbxSelectAll = (CheckBox)e.Row.FindControl("cbxSelectAll");
            cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + grvUsers.ClientID 
                + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }
        else if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal ||
            e.Row.RowState == DataControlRowState.Alternate))
        {
            SiteUser user = (SiteUser)e.Row.DataItem;
            HyperLink hlkUsername = (HyperLink)e.Row.FindControl("hlkUsername");
            if (hlkUsername != null && user != null)
            {
                hlkUsername.NavigateUrl = CustomSiteMap.UserDetail + "?id=" + user.Id;
            }
            HyperLink hlkEmail = (HyperLink)e.Row.FindControl("hlkEmail");
            if (hlkEmail != null && user != null)
            {
                hlkEmail.NavigateUrl = "mailto:" + user.Email;
            }
            Label lblActivated = (Label)e.Row.FindControl("lblActivated");
            if (lblActivated != null && user != null)
            {
                lblActivated.Text = (user.IsActivated) ? "Active" : "Inactive";
                lblActivated.ForeColor = (user.IsActivated) ? Color.Green : Color.Red;
            }
        }
    }

    protected void Pager_DataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (Convert.ToInt32(e.Item.DataItem) == CurrentPageIndex)
            {
                LinkButton lkbPageIndex = (LinkButton)e.Item.FindControl("lkbPageIndex");
                lkbPageIndex.CssClass = "page-index-selected";
            }
        }
    }

    protected void Delete_Click(object sender, EventArgs e)
    {
        List<int> usersToDelete = new List<int>();

        foreach (GridViewRow row in grvUsers.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox cbxSelect = (CheckBox)row.FindControl("cbxSelect");
                if (cbxSelect != null && cbxSelect.Checked)
                {
                    Label lblId = (Label)row.FindControl("lblId");
                    usersToDelete.Add(Convert.ToInt32(lblId.Text));
                }
            }
        }
        SiteUser.Delete(usersToDelete);
        BindGrid();
        BindPager();
    }

    protected void UpdateLock_Click(object sender, EventArgs e)
    {
        List<int> usersToLock = new List<int>();
        List<int> usersToUnlock = new List<int>();

        foreach (GridViewRow row in grvUsers.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox cbxSelect = (CheckBox)row.FindControl("cbxLocked");
                if (cbxSelect != null)
                {
                    Label lblId = (Label)row.FindControl("lblId");
                    if (cbxSelect.Checked)
                    {
                        usersToLock.Add(Convert.ToInt32(lblId.Text));
                    }
                    else
                    {
                        usersToUnlock.Add(Convert.ToInt32(lblId.Text));
                    }
                }
            }
        }
        SiteUser.UpdateLock(usersToLock, usersToUnlock);
        BindGrid();
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        BindGrid();
        BindPager();
    }
}
